/* C routines for reading files, callable from FORTRAN

Works on titania, may need byte swapping for other systems.

*/

#include <stdio.h>
#include <stdlib.h>
FILE *fp;
FILE *fgad;

/*  Abort and produce a message */

void abortmessage(char *message)
{
  printf(message);
  abort();
}

/* Open a file, read only, return iwarn=1 if an error occurs */

void open_file_(char *name, int *iwarn)
{
  char filename[512];
  int i;
  
  for (i=0; i<512; i++){
    if (name[i]==32) filename[i]=0;
    else 
      filename[i]=name[i];
  }
  
  *iwarn = 0;
  
  fp = fopen(filename,"r");
  
  if (fp==0){
    *iwarn = 1;
  }
}

/* Close the file */
void close_file_()
{
  fclose(fp);
}


void read_plane_(int *ndim, int *ipos, float *disp)
{
  long int offset;
  int nobj;

  nobj =(*ndim)*(*ndim); 
  offset = 268 + 12*nobj*(*ipos);
  if (fseek(fp,offset,SEEK_SET)!=0)
    abortmessage("Error seeking plane \n"); 

  if (fread(disp,3*sizeof(float),nobj,fp)!=nobj)
    abortmessage("Error reading in plane \n"); 
}



void read_position_info_(int *nlist, int *nind1, int *nind2, double *x, double *y,
double *z, float *ms)
{
  long int offset;
  int to_read;

  to_read = (*nind2-*nind1+1);

  /*  Read x-positions */

  //offset = 48 + 8*(*nind1) + 12;
  offset = 24 + 48 + 8*(*nind1) + 12;               // <-- to enable addition of Ali's TRAPHIC numbers
 
  if (fseek(fp,offset,SEEK_SET)!=0)
    abortmessage("Error seeking x-positions \n");
  if (fread(x,sizeof(double),to_read,fp)!=to_read)
    abortmessage("Error reading in x-position \n");

  /*  Read y-positions */

  //offset = 48 + 8*(*nind1) + 20 + 8*(*nlist);     
  offset = 24 + 48 + 8*(*nind1) + 20 + 8*(*nlist);  // <-- to enable addition of Ali's TRAPHIC numbers
  if (fseek(fp,offset,SEEK_SET)!=0)
    abortmessage("Error seeking y-positions \n");
  if (fread(y,sizeof(double),to_read,fp)!=to_read)
    abortmessage("Error reading in y-position \n");

  /*  Read z-positions */

  //offset = 48 + 8*(*nind1) + 28 + 16*(*nlist);
  offset = 24 + 48 + 8*(*nind1) + 28 + 16*(*nlist);  // <-- to enable addition of Ali's TRAPHIC numbers
  if (fseek(fp,offset,SEEK_SET)!=0)
    abortmessage("Error seeking z-positions \n");
  if (fread(z,sizeof(double),to_read,fp)!=to_read)
    abortmessage("Error reading in z-position \n");

  /*  Read masses */

  //offset = 48 + 4*(*nind1) + 36 + 24*(*nlist);
  offset = 24 + 48 + 4*(*nind1) + 36 + 24*(*nlist);  // <-- to enable addition of Ali's TRAPHIC numbers
  if (fseek(fp,offset,SEEK_SET)!=0)
    abortmessage("Error seeking masses \n");
  if (fread(ms,sizeof(float),to_read,fp)!=to_read)
    abortmessage("Error reading in masses \n");

    

}
